/**
 * 质量趋势图表组件
 * 使用ECharts展示质量变化趋势
 */
import React, { useEffect, useRef } from 'react';
import { Card, Spin, Empty, Space } from 'ant-design';
import { LineChartOutlined } from '@ant-design/icons';
import * as echarts from 'echarts';
import type { ECharts } from 'echarts';
import { useStatisticsStore } from '@/stores/statistics.store';
import './style.css';

interface QualityTrendChartProps {
  className?: string;
  height?: number;
}

export const QualityTrendChart: React.FC<QualityTrendChartProps> = ({
  className,
  height = 400,
}) => {
  const chartRef = useRef<HTMLDivElement>(null);
  const chartInstance = useRef<ECharts | null>(null);
  const { qualityTrend, loading, loadQualityTrend } = useStatisticsStore();

  useEffect(() => {
    loadQualityTrend();
  }, [loadQualityTrend]);

  useEffect(() => {
    if (!chartRef.current || loading) return;

    // 初始化图表实例
    if (!chartInstance.current) {
      chartInstance.current = echarts.init(chartRef.current);
    }

    if (qualityTrend.length === 0) {
      chartInstance.current.clear();
      return;
    }

    // 准备数据
    const dates = qualityTrend.map((item) => item.date);
    const scores = qualityTrend.map((item) => item.score);
    const structureScores = qualityTrend.map((item) => item.breakdown.structure);
    const logicScores = qualityTrend.map((item) => item.breakdown.logic);
    const readabilityScores = qualityTrend.map((item) => item.breakdown.readability);
    const originalityScores = qualityTrend.map((item) => item.breakdown.originality);

    // 配置图表选项
    const option: echarts.EChartsOption = {
      title: {
        text: '质量趋势分析',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'bold',
        },
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross',
        },
        formatter: (params: any) => {
          if (!Array.isArray(params)) return '';

          let tooltip = `<div style="padding: 8px;">`;
          tooltip += `<div style="font-weight: bold; margin-bottom: 8px;">${params[0].axisValue}</div>`;

          params.forEach((param: any) => {
            tooltip += `
              <div style="margin: 4px 0;">
                ${param.marker} ${param.seriesName}: <strong>${param.value}</strong>
              </div>
            `;
          });

          tooltip += `</div>`;
          return tooltip;
        },
      },
      legend: {
        data: ['综合质量', '结构', '逻辑', '可读性', '原创性'],
        top: 40,
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '10%',
        top: 80,
        containLabel: true,
      },
      xAxis: {
        type: 'category',
        data: dates,
        boundaryGap: false,
        axisLabel: {
          rotate: 45,
          formatter: (value: string) => {
            const date = new Date(value);
            return `${date.getMonth() + 1}/${date.getDate()}`;
          },
        },
      },
      yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: '{value} 分',
        },
        splitLine: {
          lineStyle: {
            type: 'dashed',
          },
        },
      },
      series: [
        {
          name: '综合质量',
          type: 'line',
          data: scores,
          smooth: true,
          lineStyle: {
            width: 3,
            color: '#1890ff',
          },
          itemStyle: {
            color: '#1890ff',
          },
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: 'rgba(24, 144, 255, 0.3)' },
              { offset: 1, color: 'rgba(24, 144, 255, 0.05)' },
            ]),
          },
          emphasis: {
            focus: 'series',
          },
        },
        {
          name: '结构',
          type: 'line',
          data: structureScores,
          smooth: true,
          lineStyle: {
            width: 2,
            color: '#52c41a',
          },
          itemStyle: {
            color: '#52c41a',
          },
          emphasis: {
            focus: 'series',
          },
        },
        {
          name: '逻辑',
          type: 'line',
          data: logicScores,
          smooth: true,
          lineStyle: {
            width: 2,
            color: '#722ed1',
          },
          itemStyle: {
            color: '#722ed1',
          },
          emphasis: {
            focus: 'series',
          },
        },
        {
          name: '可读性',
          type: 'line',
          data: readabilityScores,
          smooth: true,
          lineStyle: {
            width: 2,
            color: '#faad14',
          },
          itemStyle: {
            color: '#faad14',
          },
          emphasis: {
            focus: 'series',
          },
        },
        {
          name: '原创性',
          type: 'line',
          data: originalityScores,
          smooth: true,
          lineStyle: {
            width: 2,
            color: '#eb2f96',
          },
          itemStyle: {
            color: '#eb2f96',
          },
          emphasis: {
            focus: 'series',
          },
        },
      ],
    };

    chartInstance.current.setOption(option);

    // 响应式处理
    const handleResize = () => {
      chartInstance.current?.resize();
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, [qualityTrend, loading]);

  // 清理
  useEffect(() => {
    return () => {
      chartInstance.current?.dispose();
    };
  }, []);

  return (
    <Card
      className={`quality-trend-chart ${className || ''}`}
      title={
        <Space>
          <LineChartOutlined />
          <span>质量趋势</span>
        </Space>
      }
    >
      <Spin spinning={loading}>
        {qualityTrend.length === 0 && !loading ? (
          <Empty description="暂无数据" style={{ padding: '40px 0' }} />
        ) : (
          <div ref={chartRef} style={{ width: '100%', height: `${height}px` }} />
        )}
      </Spin>
    </Card>
  );
};

export default QualityTrendChart;
